// mixins/trackingMixin.js
import ComponentTracker from '@ct/component-gallery-tracking-sdk'; // 修改为默认导入
// import { getInfo } from '../utils/index.js';

export const trackingMixin = {
  data() {
    return {
      userInfo: null,
      tracker: null
    };
  },
  async created() {
    this.userInfo = this.$store?.getters?.userInfo ?? JSON.parse(localStorage.getItem('$loginInfo'));
    // if (!this.userInfo) {
    //   try {
    //     const res = await getInfo();
    //     if (res.code === 200) {
    //       this.userInfo = res.user;
    //     }
    //   } catch (err) {
    //     console.log('获取用户信息失败:', err);
    //   }
    // }
    this.initTrack();
    // 组件加载完成时上报数据
    this.trackComponentUsage();
  },
  mounted() {
    // 添加页面刷新和关闭的监听
    if (typeof window !== 'undefined') {
      // 页面刷新或关闭时
      window.addEventListener('beforeunload', this.handlePageUnload);
    }
  },
  beforeDestroy() {
    // 组件销毁时上报数据
    // 移除事件监听
    if (typeof window !== 'undefined') {
      window.removeEventListener('beforeunload', this.handlePageUnload);
    }
    // 组件销毁时删除数据库
    this.deleteTrackingDatabase();
  },
  methods: {
    initTrack() {
      // 使用 new 创建实例
      this.tracker = new ComponentTracker({
        userInfo: {
          admin: this.userInfo?.admin,
          adminNew: this.userInfo?.adminNew,
          aesPhoneNumber: this.userInfo?.aesPhoneNumber,
          appVerCode: this.userInfo?.appVerCode,
          industryCode: this.userInfo?.industryCode,
          platformCode: this.userInfo?.platformCode,
          platformLevel: this.userInfo?.platformLevel,
          platformName: this.userInfo?.platformName,
          tenantId: this.userInfo?.tenantId,
          tenantInfo: this.userInfo?.tenantInfo,
          userId: this.userInfo?.userId,
          userName: this.userInfo?.userName
        },
        isComponent: false,
        retryConfig: {
          enable: true,
          maxRetries: 3,
          retryInterval: 60000
        },
        // debug: true
      });
    },
    // 处理页面刷新或关闭
    handlePageUnload(event) {
      // 删除数据库
      this.deleteTrackingDatabase();
    },
    // 删除数据库的方法
    async deleteTrackingDatabase() {
      try {
        await this.tracker.deleteDatabase();
        if (process.env.NODE_ENV === 'development') {
          console.log('埋点数据库已删除');
        }
      } catch (error) {
        if (process.env.NODE_ENV === 'development') {
          console.error('删除数据库失败:', error);
        }
      }
    },
    // 上报组件使用数据
    trackComponentUsage() {
      // 上报数据
      this.tracker.track({
        eventType: 'screen',
        screenData: this.$options.packageInfo.screenData || 'Unknown',
        timestamp: Date.now()
      });
    }
  }
};
